package com.elitel.frame.base.controller;

import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;


import com.alibaba.fastjson.JSON;
//import com.elitel.common.redis.RedisDbIndex;
//import com.elitel.common.redis.service.RedisCacheService;
import com.elitel.frame.base.component.RedisCatchCode;
import com.elitel.frame.base.service.CodeService;
import com.elitel.frame.main.entity.CodeSystem;
import com.elitel.frame.main.entity.CodeType;
import com.elitel.frame.main.entity.ext.BasicPaging;
import com.elitel.frame.main.entity.ext.Census;
import com.elitel.frame.main.entity.ext.CodeSys;
import com.elitel.frame.main.entity.vo.CodeTree;
import com.elitel.frame.main.entity.vo.PageResponseVo;

/**
 * 编码控制类
 *
 * @author dingdaifu
 */
@Controller
@RequestMapping("/system/code")
public class CodeController {

    @Resource
    private CodeService codeServiceImpl;

//    @Resource
//    private RedisCacheService redisCacheService;

    @Resource
    private RedisCatchCode redisCatchCode;

    //private static final RedisDbIndex rdi =RedisDbIndex.ZERO;
    private static final Logger logger = LoggerFactory.getLogger(PerformanceMonitorController.class);

//	@Autowired
//    private JmsTemplate jmsTemplate;
//	@Resource(name = "serverQueueDestination")
//	private Destination destination;
//	@Autowired
//    private AmqpTemplate amqpTemplate;

    /**
     * <pre>showInformation(推送前台性能信息)
     * @author：FanWenquan
     * @date：2017年9月21日 下午3:54:43
     * @return</pre>
     */
    @RequestMapping("/showInformation")
    @ResponseBody
    public Object showInformation() {
        StringBuffer strtxt = new StringBuffer();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
//		try {
//			while(true) {
//				Object message = amqpTemplate.receiveAndConvert("serverQueueDestination");
////				TextMessage message = (TextMessage)jmsTemplate.receive(destination);
//				if(null != message && !"".equals(message)){
//					strtxt.append(message.toString());
//				}else{
//					break;
//				}
//			}
//		} catch (Exception e) {
//			logger.error(e.getMessage(),e);
//		}

        return strtxt;
    }

    @RequestMapping("/getCodeTree")
    @ResponseBody
    public List<CodeType> getCodeTree(HttpServletRequest request) {

        List<CodeType> list = codeServiceImpl.getCodeTree();
        return list;
    }

    @RequestMapping("/getCodeSystem")
    @ResponseBody
    public List<CodeSystem> getCodeSystems(HttpServletRequest request) {
        String sysId = null;
        try {
            sysId = new String(request.getParameter("sysId").getBytes("iso-8859-1"), "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        List<CodeSystem> list = codeServiceImpl.getCodeSystem(sysId);
        return list;
    }


    @RequestMapping(value = "/insertCodeSystem", method = RequestMethod.POST, consumes = "application/json")
    @ResponseBody
    public Map<String, Object> insertCodeSystem(@RequestBody CodeSys cSys, HttpServletRequest request) {
//        int rdi = RedisDbIndex.value;
        Map<String, Object> map = new HashMap<String, Object>();
        CodeSystem codeSystem = new CodeSystem();
        try {
            String code = cSys.getCode();
            String content = cSys.getContent();
            String remake = cSys.getRemake();
            String sysId = cSys.getSysId();
            codeSystem.setCode(code);
            codeSystem.setContent(content);
            codeSystem.setFkSysId(Integer.parseInt(sysId));
            codeSystem.setRemake(remake);
            String message = codeServiceImpl.insetCodeSystem(codeSystem);
            map.put("message", message);
            if (map.get("message") == "success") {
//                String key = "CODE_" + cSys.getSysId();
//                PageResponseVo<CodeSystem> codeAll = codeServiceImpl.getAllCode(sysId);
//                String codeString = JSONObject.fromObject(codeAll).toString();
//                redisCacheService.saveObject(key, codeString, rdi);
                redisCatchCode.refreshCodeSystem(cSys.getSysId());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return map;
    }

    @RequestMapping("/deleteCodeSystem")
    @ResponseBody
    public Map<String, Object> deleteCodeSystem(HttpServletRequest request) {
//        int rdi = RedisDbIndex.value;
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            String id = new String(request.getParameter("keys").getBytes("iso-8859-1"), "utf-8");
            CodeSystem cSys = codeServiceImpl.getCodeOne(id);
            String message = codeServiceImpl.deleteCodeSystem(id);
            map.put("message", message);
            if (map.get("message") == "success") {
//                String key = "CODE_" + cSys.getFkSysId();
//                PageResponseVo<CodeSystem> codeAll = codeServiceImpl.getAllCode(String.valueOf(cSys.getFkSysId()));
//                String codeString = JSONObject.fromObject(codeAll).toString();
//                redisCacheService.saveObject(key, codeString, rdi);
                redisCatchCode.refreshCodeSystem(cSys.getFkSysId().toString());
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return map;
    }

    @RequestMapping(value = "updateCodeSystem", method = RequestMethod.POST, consumes = "application/json")
    @ResponseBody
    public Map<String, Object> updateCodeSystem(@RequestBody CodeSys codeSys, HttpServletRequest request) {
//        int rdi = RedisDbIndex.value;
        Map<String, Object> map = new HashMap<String, Object>();
        CodeSystem codeSystem = new CodeSystem();
        try {
            String id = codeSys.getId();
            String code = codeSys.getCode();
            String content = codeSys.getContent();
            String remake = codeSys.getRemake();
            codeSystem.setId(Long.parseLong(id));
            codeSystem.setCode(code);
            codeSystem.setContent(content);
            codeSystem.setRemake(remake);
            String message = codeServiceImpl.updateCodeSystem(codeSystem);
            CodeSystem cSys = codeServiceImpl.getCodeOne(id);
            map.put("message", message);
            if ("success".equals(map.get("message"))) {
//                String key = "CODE_" + cSys.getFkSysId();
//                PageResponseVo<CodeSystem> codeAll = codeServiceImpl.getAllCode(String.valueOf(cSys.getFkSysId()));
//                String codeString = JSONObject.fromObject(codeAll).toString();
//                redisCacheService.saveObject(key, codeString, rdi);
                redisCatchCode.refreshCodeSystem(cSys.getFkSysId().toString());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return map;
    }

    @RequestMapping("/selectCodeOne")
    @ResponseBody
    public CodeSystem slectCodeOne(HttpServletRequest request) {
        String id = null;
        try {
            id = new String(request.getParameter("key").getBytes("iso-8859-1"), "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        CodeSystem codeSystem = codeServiceImpl.selectCodeOne(id);
        return codeSystem;
    }

    @RequestMapping("/selectCodeSystem")
    @ResponseBody
    public List<CodeSystem> selectCodeSystem(HttpServletRequest request) {
        String sysId = null;
        try {
            sysId = new String(request.getParameter("sysId").getBytes("iso-8859-1"), "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        List<CodeSystem> list = codeServiceImpl.selectCodeSystem(sysId);
        return list;
    }

    @RequestMapping("/selectCodeType")
    @ResponseBody
    public List<Census> selectCodeType(HttpServletRequest request) {
//		int rdi = RedisDbIndex.value;
//		String key = "CODE_type";
//		List<CodeTree> list2 = new ArrayList<CodeTree>();
//		if(redisCacheService.stringExists(key, rdi)){
//			list2 =	redisCatchCode.getRedisCatchCodeType(key);
//		}else {
//			List<CodeType> list = codeServiceImpl.selectCodeType();
//			for(CodeType codeType:list){
//				CodeTree codeTree = new CodeTree();
//				codeTree.setId(codeType.getId());
//				codeTree.setName(codeType.getTypeName());
//				list2.add(codeTree);
//			}
//			String codeType = JSON.toJSONString(list2);
//			redisCacheService.saveObject(key, codeType, rdi);
//		}
        List<CodeTree> list2 = redisCatchCode.getRedisCatchCodeType();
        List<Census> list = new ArrayList<Census>();
        for (CodeTree c : list2) {
            Census census = new Census();
            census.setPid(String.valueOf(0));
            census.setId(String.valueOf(c.getId()));
            census.setName(c.getName());
            list.add(census);
        }
        return list;
    }

    @RequestMapping("/paging")
    @ResponseBody
    public PageResponseVo<CodeSystem> getFenYe(HttpServletRequest request) {
//        int rdi = RedisDbIndex.value;
        PageResponseVo<CodeSystem> paVo = null;
        try {
            String sysId = new String(request.getParameter("sysId").getBytes("iso-8859-1"), "utf-8");
            String pageNo = new String(request.getParameter("pageNo").getBytes("iso-8859-1"), "utf-8");
            String pageSize = new String(request.getParameter("pageSize").getBytes("iso-8859-1"), "utf-8");
//			String key = "CODE_"+sysId;
//			if (redisCacheService.stringExists(key, rdi)) {
//				paVo = redisCatchCode.getRedisCatchCode(sysId, pageNo, pageSize);
//			}else {
//				paVo = codeServiceImpl.getFenYe(pageNo,pageSize,sysId);
//				PageResponseVo<CodeSystem> codeAll = codeServiceImpl.getAllCode(sysId);
//				String codeString = JSON.toJSONString(codeAll);
//				redisCacheService.saveObject(key, codeString, rdi);
//			}
            paVo = redisCatchCode.getRedisCatchCode(sysId, pageNo, pageSize);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return paVo;
    }

    @RequestMapping(value = "/insertCodeType", method = RequestMethod.POST, consumes = "application/json")
    @ResponseBody
    public Map<String, Object> insertCodeType(@RequestBody BasicPaging basicPaging, HttpServletRequest request) {
//        int rdi = RedisDbIndex.value;
        Map<String, Object> map = new HashMap<String, Object>();
        String message = "fail";
//        String key = "CODE_type";
//        List<CodeTree> list2 = new ArrayList<CodeTree>();
        try {
            String name = basicPaging.getName();
            String remakes = basicPaging.getRemakes();
            CodeType codeType = new CodeType();
            codeType.setRemake(remakes);
            codeType.setTypeName(name);
            message = codeServiceImpl.insertCodeType(codeType);
            if ("success".equals(message)) {
//                List<CodeType> list = codeServiceImpl.selectCodeType();
//                for (CodeType codeTypes : list) {
//                    CodeTree codeTree = new CodeTree();
//                    codeTree.setId(codeTypes.getId());
//                    codeTree.setName(codeTypes.getTypeName());
//                    list2.add(codeTree);
//                }
//                String codeTypeing = JSON.toJSONString(list2);
//                redisCacheService.saveObject(key, codeTypeing, rdi);
                redisCatchCode.refreshCodeType();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        map.put("message", message);
        return map;
    }

    @RequestMapping("/selectTypeOne")
    @ResponseBody
    public CodeType selectCodeTypeOne(HttpServletRequest request) {
//        int rdi = RedisDbIndex.value;
        CodeType codeType = null;
        try {
            String id = new String(request.getParameter("key").getBytes("iso-8859-1"), "utf-8");
//            String key = "CODE_" + id;
//            if (redisCacheService.stringExists(key, rdi)) {
//                codeType = redisCatchCode.selectCodeOne(key);
//            } else {
//                codeType = codeServiceImpl.selectCodeTypeOne(id);
//                String codeTypeOne = JSONObject.fromObject(codeType).toString();
//                redisCacheService.saveObject(key, codeTypeOne, rdi);
//            }
            codeType = redisCatchCode.selectCodeOne(id);
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return codeType;
    }

    @RequestMapping("/deleteType")
    @ResponseBody
    public Map<String, Object> deleteCodeType(HttpServletRequest request) {
//        int rdi = RedisDbIndex.value;
        Map<String, Object> map = new HashMap<String, Object>();
        String message = null;
//        String key = "CODE_type";
//        List<CodeTree> list2 = new ArrayList<CodeTree>();
        try {
            String id = new String(request.getParameter("keys").getBytes("iso-8859-1"), "utf-8");
            message = codeServiceImpl.deleteCodeType(Integer.parseInt(id));
            if ("success".equals(message)) {
//                List<CodeType> list = codeServiceImpl.selectCodeType();
//                for (CodeType codeTypes : list) {
//                    CodeTree codeTree = new CodeTree();
//                    codeTree.setId(codeTypes.getId());
//                    codeTree.setName(codeTypes.getTypeName());
//                    list2.add(codeTree);
//                }
//                String codeTypeing = JSON.toJSONString(list2);
//                redisCacheService.saveObject(key, codeTypeing, rdi);
                redisCatchCode.refreshCodeType();
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        map.put("message", message);
        return map;
    }

    @RequestMapping(value = "/updateCodeType", method = RequestMethod.POST, consumes = "application/json")
    @ResponseBody
    public Map<String, Object> updateCodeType(@RequestBody BasicPaging cType, HttpServletRequest request) {
//        int rdi = RedisDbIndex.value;
        Map<String, Object> map = new HashMap<String, Object>();
        String message = null;
//        String key = "CODE_type";
//        List<CodeTree> list2 = new ArrayList<CodeTree>();
        try {
            String id = cType.getId();
            String name = cType.getName();
            String remake = cType.getRemakes();
            CodeType codeType = new CodeType();
            codeType.setId(Integer.parseInt(id));
            codeType.setRemake(remake);
            codeType.setTypeName(name);
            message = codeServiceImpl.updateCodeType(codeType);
            if ("success".equals(message)) {
//                List<CodeType> list = codeServiceImpl.selectCodeType();
//                for (CodeType codeTypes : list) {
//                    CodeTree codeTree = new CodeTree();
//                    codeTree.setId(codeTypes.getId());
//                    codeTree.setName(codeTypes.getTypeName());
//                    list2.add(codeTree);
//                }
//                String codeTypeing = JSON.toJSONString(list2);
//                redisCacheService.saveObject(key, codeTypeing, rdi);
                redisCatchCode.refreshCodeType();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        map.put("message", message);
        return map;
    }
}
